﻿using System.Net.Sockets;
using Net.Public.Helper;
using Net.Public.Msg;

namespace Net.Public.Server
{
    public class ClientSockt
    {
        public bool IsConnect
        {
            get => this._client.Connected;
        }
        private bool isOnline = false;
        public bool IsOnline
        {
            get => isOnline;
            set => isOnline = value;
        }
        private MsgHandler _msgHandler;

        /// <summary>
        /// 服务器打通的联系通道
        /// </summary>
        private Socket _client;
        
        public ClientSockt(Socket client)
        {
            this._client = client;
            _msgHandler = new MsgHandler();
        }


        public void SendMsgToClient(BaseMsg msg)
        {
            try
            {
                if (IsConnect)
                    _msgHandler.SendMsg(_client,msg);
            }
            catch (Exception e)
            {
                Debugger.Log(e.Message);
                Close();
                throw new Exception("服务器发送信息给客户端出现问题");
            }
        }

        public (BaseMsg,bool) ReceiveMsgFromClient()
        {
            if (!IsConnect)
                return default;
            try
            {
                if (_client.Available > 0)
                {
                    byte[] result = new byte[1024 * 5];
                    int receiveNum = _client.Receive(result);
                    _msgHandler.ReceiveMsg(result,receiveNum);
                }
                (BaseMsg, bool) msg = _msgHandler.HandlerMsg();
                return msg;
            }
            catch (Exception e)
            {
                Debugger.Log(e.Message);
                Close();
                throw new Exception("服务器接收信息给客户端出现问题");
            }
            return default;
        }
        
        public void Close(bool reuseSocket = false)
        {
            if (IsConnect)
            {
                _client.Shutdown(SocketShutdown.Both);
                _client.Disconnect(reuseSocket);
                _client.Close();
                _msgHandler.Close();
                _msgHandler = null;
            }
        }
    }
}